<template lang="">
  <div class="nav-menu">
    <!-- 左侧顶部logo -->
    <div class="logo">
      <img class="img" src="~@/assets/img/logo.svg" alt="logo">
      <span v-if="!props.isFold">Vue3+TS</span>
    </div>
    <!-- 左侧权限菜单 -->
    <!-- 注意，default-active的属性值需要对应每个submenu的唯一标识index -->
    <el-menu
      :default-active="activeMenu"
      active-text-color="#ffd04b"
      background-color="#001529"
      class="el-menu-vertical"
      text-color="#fff"
      :unique-opened="true"
      :collapse="props.isFold"
    >
    <!-- 循环遍历userMenu用户菜单权限 -->
      <template v-for="(item,index) in userMenu" :key="item.id">
      <!-- 判断当前遍历的权限是否有子权限，如果有则渲染submenu然后继续遍历子权限，目前最多2层遍历 -->
        <template v-if="item.children">
          <el-sub-menu :index="item.id+''">
            <template #title>
              <i v-if="item.icon" :class="item.icon"></i>
              <span>{{item.name}}</span>
            </template>
            <template v-for="(subItem,subIndex) in item.children">
              <el-menu-item class="el-menu-item" :index="subItem.id+''" @click="handleMenuItemClick(subItem)">
                <i v-if="subItem.icon" :class="subItem.icon"></i>
                <span>{{subItem.name}}</span>
              </el-menu-item>
            </template>
          </el-sub-menu>
        </template>
        <!-- 当前遍历的权限没有子权限，所以直接通过menu-item渲染 -->
        <template v-else>
          <el-menu-item class="el-menu-item" @click="handleMenuItemClick(item)">
            <i v-if="item.icon" :class="item.icon"></i>
            <span>{{item.name}}</span>
          </el-menu-item>
        </template>
      </template>
    </el-menu>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from '@vue/reactivity';
import { useStore } from '@/store'
import { useRouter } from 'vue-router'
import { pathMapToMenu } from '@/utils/map-menus';
import { useRoute } from 'vue-router';
const router = useRouter()
const store = useStore()
const route = useRoute()
const props = defineProps(['isFold'])

// 获取login的state数据中的userMenu数据，并通过计算属性返回给一个新变量保存以便模板中简便写法
const userMenu = computed(()=>store.state.login.userMenu)
// 点击后跳转到对应的url
const handleMenuItemClick = (item:any) => {
    router.push(item.url)
}
// 处理刷新时菜单action错误
const menu = pathMapToMenu(userMenu.value,route.path)
const activeMenu = ref(menu.id + '')
</script>

<style scoped lang="less">
.nav-menu{
  height: 100%;
  background-color: #123553;
  color: white;
  .logo{
    display: flex;
    padding: 10px;
    align-items: center;
    justify-content: center;
    gap: 20px;
    background-color: #001529;
    .img{
      width: 45px;
    }
    span{
      font-size: 20px;
      letter-spacing: 1px;
      font-weight: 700;
    }
  }
  .el-menu-vertical{
    background-color: #123553 !important;
      .el-menu-item{
      padding-left: 50px !important;
    }
  }
}
</style>
